package cn.wgx.commons.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 邮件发送工具
 */
public class EMailUtil {


    private static Logger logger = LoggerFactory.getLogger(EMailUtil.class);

    private static String EMAIL_HOST = "smtp.qq.com";
    private static String EMAIL_USERNAME = "sdf4saas@qq.com";
    private static String EMAIL_PASSWORD = "dodxecccgnlnbjbb";
//    private static String EMAIL_HOST = "mail.sxycy.cn";
//    private static String EMAIL_USERNAME = "admin";
//    private static String EMAIL_USERNAME_FROM = "admin@sxycy.cn";
//    private static String EMAIL_PASSWORD = "admin";
    private static Properties prop = new Properties();

    static {
        //初始化
//        String host = Global.getConfig("email.host");
//        String username = Global.getConfig("email.username");
//        String password = Global.getConfig("email.password");
//
//        EMAIL_HOST = host==null?EMAIL_HOST:host;
//        EMAIL_USERNAME = username==null?EMAIL_USERNAME:username;
//        EMAIL_PASSWORD = password==null?EMAIL_PASSWORD:password;

        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.socketFactory", sf);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.imap.ssl.socketFactory.class",
                    "DummySSLSocketFactory");
            prop.put("mail.smtp.startssl.enable", "true");
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.smtp.timeout", "10000");
//            prop.put("mail.smtp.port", "465");
//            prop.put("mail.smtp.port", "587");
//            prop.put("mail.smtp.port", "25");
        } catch (GeneralSecurityException e) {
            logger.error("初始化邮件参数错误.", e.getMessage());
        }
    }

    public static void  main(String a[]){
        sendSimpleEMail("3857756@qq.com",
                "testTitle",
                "您正在注册素材库网站: 您的验证码为: 456123");
    }

    private static JavaMailSenderImpl getMailSender(){
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        senderImpl.setHost(EMAIL_HOST);
        senderImpl.setUsername(EMAIL_USERNAME);
        senderImpl.setPassword(EMAIL_PASSWORD);
        senderImpl.setJavaMailProperties(prop);
        return senderImpl;
    }

    /**
     * 发送简单文本邮件
     * @param toMail
     * @param title
     * @param mssage
     */
    public static boolean sendSimpleEMail(String toMail, String title, String mssage){
        JavaMailSenderImpl senderImpl = getMailSender();
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(toMail);  //收信人邮箱
        mailMessage.setFrom(EMAIL_USERNAME); //发送人邮箱
        mailMessage.setSubject(title);  //邮件主题
        mailMessage.setText(mssage);  //邮件内容
        senderImpl.setJavaMailProperties(prop);
        try {
            senderImpl.send(mailMessage);
            return true;
        } catch (MailException e) {
            logger.error(e.getMessage());
            return false;
        }
    }


    /**
     * 发送富文本邮件
     * @param toMail
     * @param title
     * @param message
     * @throws GeneralSecurityException
     * @throws MessagingException
     */
    public  static boolean sendMimeMail(String toMail, String title, String message) throws GeneralSecurityException, MessagingException {
        JavaMailSenderImpl senderImpl = getMailSender();
        MimeMessage mail = senderImpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mail,true);
        helper.setFrom(EMAIL_USERNAME);
        helper.setTo("");
        helper.setSubject(title);
        helper.setText(message);
//        FileSystemResource mailImage = new FileSystemResource("src/main/webapp/files/images/mail.png");
//        helper.addAttachment("mail.png", mailImage);
        try {
            senderImpl.send(mail);
        } catch (MailException e) {
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }


    /**
     * 发送HTML全文本邮件
     * @param toMail
     * @param title
     * @param message
     * @throws GeneralSecurityException
     * @throws MessagingException
     */
    public static void sendHTMLMail(String toMail, String title, String message) throws GeneralSecurityException, MessagingException{
        JavaMailSenderImpl senderImpl = getMailSender();
        senderImpl.setDefaultEncoding("UTF-8");
        MimeMessage mail = senderImpl.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mail,true);
        helper.setFrom(EMAIL_USERNAME);
        helper.setTo(toMail);
        helper.setSubject(title);
        StringBuilder html = new StringBuilder();
        html.append(message);
//        html.append("<html>")
//                .append("<body>")
//                .append("<h2>Goser,你好</h2>")
//                .append("<p>这是一个测试。</p>")
//                .append("<img src='cid:mailImage'/>")
//                .append("<p>THANKS</p>")
//                .append("</body>")
//                .append("</html>");
        helper.setText(html.toString(),true);
        senderImpl.send(mail);
        System.out.println("html email was send to: " + toMail);
    }
}
